#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@File    : mngs_plot_coverage.py
@Author  : Bing Liang
@Email   : believer19940901@gmail.com
@Date    : 2025/9/23 16:43
@Description : 绘制全基因组覆盖率图（单染色体）
"""
from argparse import Namespace, ArgumentParser

import pandas as pd
import matplotlib.pyplot as plt


def main(args: Namespace):

    # 读取数据
    df = pd.read_csv(args.in_depth, sep='\t', header=None, names=['chrom', 'position', 'depth'])

    # 将位点转换为窗口
    df["window"] = ((df["position"] - 1) // args.window_size) + 1

    # 计算每个窗口的平均深度
    coverage_summary = df.groupby("window")["depth"].mean().reset_index()

    # --------
    # 绘图
    # --------

    # 设置画布
    plt.figure(figsize=(12, 6))

    # 绘制内容
    plt.bar(coverage_summary["window"], coverage_summary["depth"],
            width=0.8, color='orange')

    # 设置X轴标题
    plt.xlabel(f"Nucleotide Position ({args.window_size // 1000}K)")

    # 设置Y轴标题
    plt.ylabel("Reads Number")

    # 设置标题
    plt.title(args.title.strip())

    plt.tight_layout()
    plt.savefig(args.out_png, dpi=300)
    plt.savefig(args.out_pdf)
    plt.close()


if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument("-i", "--in_depth", type=str, required=True)
    parser.add_argument("-w", "--window_size", type=int, required=False, default=10_000)
    parser.add_argument("-g", "--out_png", type=str, required=True)
    parser.add_argument("-f", "--out_pdf", type=str, required=True)
    parser.add_argument("-t", "--title", type=str, required=False, default="Coverage")
    main(parser.parse_args())

